<?php

namespace Home\Controller;
use Common\Controller\FirstendController;

class WeixinController extends FirstendController {
	 
	private $_itkconfig = null; 
	public function _initialize() {
		parent::_initialize();
		if(C('itk_site_cache')){
			$file = 'ItemsSite';
			if(false === $this->_itkconfig = S($file)){
				$api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
				$this->_itkconfig = unserialize($api_config);
				S($file,$this->_itkconfig);
			}
		}else{
			$api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
			$this->_itkconfig = unserialize($api_config);
		} 
	}
    public function index() { 
		import("ITK.weixin.wechat"); 			
		import("ITK.weixin.TPWechat"); 
		import("ITK.weixin.MyWechatUtil"); 
		 			
		$options = array(
				'token'=>C('itk_weixin_token',null,''), //填写你设定的key
				'encodingaeskey'=>'', //填写加密用的EncodingAESKey
				'appid'=>C('itk_weixin_key',null,''), //填写高级调用功能的app id, 请在微信开发模式后台查询
				'appsecret'=>C('itk_weixin_secret',null,'') //填写高级调用功能的密钥
				); 
				
				
		
		 		
		$weObj = new \TPWechat($options);
					 	 
		$weObj->valid();//明文或兼容模式可以在接口验证通过后注释此句，但加密模式一定不能注释，否则会验证失败
		$type = $weObj->getRev()->getRevType(); 
		
		switch($type) {
			case \TPWechat::MSGTYPE_TEXT:
					$content = $weObj->getRev()->getRevContent();  
				//	$weObj->text("小二正在努力搜索中... ")->reply();
					// 根据微信查找状态判断（ 0 - 云库  1- 超级搜索）

					$wx_keyword_mod = D('Weixinkeyword');
					$resKeyword = $wx_keyword_mod->where(array('keyword' => $content))->find();
					if(empty($resKeyword))
					{
					    $content = getBetween($content,"（","）");
					    if(C('itk_wx_search') == 1){
					        $url=C('itk_wap_url').U('Super/index',array('keyword'=>$content));
					        $sUrl = getSinaShortUrl($url);
					        $weObj->text("小二已为您查找,请点击链接查看 :".$sUrl)->reply();
					        break;
					    }
						$openid = $weObj->getRev()->getRevFrom(); 
						$currentPage = 1;
						if( S($openid.$content))
						{
							$currentPage = S($openid.$content) +1;
							S($openid.$content,$currentPage,60);
						}else
						{
							S($openid.$content,1,60);
						}
							 
					 
						$taodianjin = C('itk_taojindian_html');
						if (strpos($taodianjin, "text/javascript")) {
							$pid = get_word($taodianjin, 'pid: "' , '"');
						} else {
							$pid = $taodianjin;
						} 
						$news = array();  
						$tb_top = $this->_get_top();
						$req = $tb_top->load_api('ItaokeRobotSearchRequest');
						$req->putOtherTextParam('pid',$pid);
						$req->putOtherTextParam('qpid',C('itk_queqiao_pid')); 
						$req->putOtherTextParam('key',$content);	
						$req->putOtherTextParam('page',$currentPage);	
						$req->putOtherTextParam('perpage',6);
						$resp = (array)$tb_top->execute($req); 
						if(isset($resp['data']) &&isset($resp['data']['result']))
						{ 
							foreach($resp['data']['result'] as $val)
							{
								if(isset($val['title']))
								{ 
										$arr  =  array();
										$arr  ['Title'] =  $val['title'] ;
										$arr  ['Description'] = $val['price'];
										$arr  ['PicUrl'] =$val['pic_url'];
										//$arr   ['Url'] = $val['qwurl'];
										$arr  ['Url'] = C('itk_wap_url').U('So/detail',array('num_iid'=>$val['num_iid']));
										 

										array_push($news,$arr);
								}
								
							}
						}
						// 关键词搜索返回多个
						if(count($news)>0)
						{
							$weObj->news( $news)->reply(); 		
						}else
						{
						    // 搜索返回一个  或者没有  可能代表分享转换
							if(isset($resp['status'])&&$resp['status']=='0000')
							{
								S($openid.$content,0,60);
								$weObj->text("抱歉,好像没有找到哦,试试超级搜索吧 ")->reply();	
							}else
							{
								$weObj->text($resp['msg'])->reply();	
							}
							
						} 				
						
					}else
					{
						switch($resKeyword['type'])
						{
							case 1:
									$contentTextReply = \MyWechatUtil::replaceEmoji(htmlspecialchars_decode($resKeyword['content']));
									$contentTextReply = str_replace("[内部换行]","\r\n",$contentTextReply ) ; 
									$contentTextReply = strip_tags($contentTextReply) ; 
									$weObj->text($contentTextReply)->reply();  break;//文字信息
							case 2:$weObj->image($resKeyword['media_id'])  ->reply();  break;//图片信息
							case 3: 
									$media_id = $resKeyword['media_id'];
									$foverMedia = $weObj->getForeverMedia($media_id);
									$news = array();
									 
									foreach($foverMedia['news_item'] as $foverBean)
									{
										//$foverBean
										$arr  =  array();
										$arr  ['Title'] = $foverBean['title'];
										$arr  ['Description'] = $foverBean['digest'];
										$arr  ['PicUrl'] = $foverBean['thumb_url'];
										$arr   ['Url'] = $foverBean['url'];
										array_push($news,$arr);
									}
									$weObj->news( $news)  ->reply(); 
								 
									break;//图文信息
						}
						
					} 
				
					break;
			case \TPWechat::MSGTYPE_EVENT:
					$eventBean = $weObj->getRevEvent();
					 
					if($eventBean['event'] == 'CLICK')
					{
						$key = $eventBean['key'];
						switch($key)
						{
							case 'sign':
								
								$user = M('user');
								$openid = $weObj->getRev()->getRevFrom();
								$whereData ['wxopenid'] = $openid;  
								$userBean = $user->where($whereData)->find(); //$userBean['id']
								$resultSIGN  = sign($userBean['id'],$userBean['username']);
								$resultSIGN_Msg = str_replace("<br/>","\r\n",$resultSIGN['msg'] );
								if($resultSIGN['status']==0){	//成功
									$contentTip=C('itk_wxtips.sign');
									$other=array(
										'username'=>$userBean['username'],
										'score'=>$resultSIGN['score'],
									);
									$resultSIGN_Msg= wxtips_replace($contentTip,$other);
								}else{							//失败
									$contentTip=C('itk_wxtips.asign');
									$other=array(
										'username'=>$userBean['username'],
										'score'=>$resultSIGN['score'],
									);
									$resultSIGN_Msg= wxtips_replace($contentTip,$other);
								}
			
								$weObj->text($resultSIGN_Msg)->reply();

								break;
							case 'user':$weObj->text('个人中心')->reply(); break;
							case 'lottery':$weObj->text('积分抽奖')->reply(); break;
							case 'poster':
							
								
								$user = M('user');
								$openid = $weObj->getRev()->getRevFrom();
								$whereData ['wxopenid'] = $openid;  
								$userBean = $user->where($whereData)->find(); //$userBean['id']
								if(empty($userBean))
								{
									$weObj->text('您未产生用户对应数据，请联系后台重新申请')->reply();
								}else
								{
									$WxheadPath = ''; 
									if(!file_exists($_SERVER['DOCUMENT_ROOT'] .'/'.'data/upload/site/wxheade_'.$userBean['id'].'.jpg'))
									{
										$wxheaderpicurl =  substr($userBean['wxheadpic'],0,strlen($userBean['wxheadpic'])-1).'96' ;
										$WxHeadImage= \MyWechatUtil::getImage ( $wxheaderpicurl ,'data/upload/site/','wxheade_'.$userBean['id'].'.jpg',1)  ;
										$WxheadPath = $_SERVER['DOCUMENT_ROOT'] .'/'.$WxHeadImage['save_path'];  
										//$weObj->text('正在为您准备请再点击一次')->reply(); return;
									}else
									{
										$WxheadPath = $_SERVER['DOCUMENT_ROOT'] .'/'.'data/upload/site/wxheade_'.$userBean['id'].'.jpg';
									}
									$qrArry =  $weObj->getQRCode($userBean['id'],0,2592000); 
									//$qrArry['url'] 
									//\MyWechatUtil::savePicToServer("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$qrArry['ticket']);
									$QrImage =  \MyWechatUtil::getImage("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$qrArry['ticket'],'data/upload/site/','qrcodeitaoke_'.date('YmdHis'). substr(md5(time()), 0, 6).'.jpg');
									
									$QrMerageFilePath = 'data/upload/site/qrMerge'.date('YmdHis'). substr(md5(time()), 0, 6).'.jpg';//合成后的文件
									
									
									\MyWechatUtil::GenQrV(''.$_SERVER['DOCUMENT_ROOT'] .'/static/weixin/assets/sell/images/default_poster_preview/poster_preview_'.C('itk_wxscore_rule.poster_type',null,1).'.png',''.$_SERVER['DOCUMENT_ROOT'] .'/'.$QrImage['save_path'],$userBean['wxnickname'],''.$_SERVER['DOCUMENT_ROOT'] .'/'.$QrMerageFilePath,C('itk_wxscore_rule.poster_type',null,1),
									$WxheadPath//''.$_SERVER['DOCUMENT_ROOT'] .'/'.$WxHeadImage['save_path']//
									);
			
									$media['media'] = '@'.$_SERVER['DOCUMENT_ROOT'] .'/'.$QrMerageFilePath;
									 
									$mediaArry = $weObj->uploadMedia($media,'image');  
									
									$weObj->image($mediaArry['media_id']) ->reply();	
								} 
								break;
							case 'integralmall':$weObj->text('兑换商城')->reply(); break;
							case 'resetpwd':
								
								$user = M('user');
								$openid = $weObj->getRev()->getRevFrom();
								$whereData ['wxopenid'] = $openid; 
								$userBean = $user->where($whereData)->find();
								if(!empty($userBean))
								{
									$pwd = substr(md5(time()), 0, 6);
									$userBean['password'] = md5($pwd);
									$user->where($whereData)->save($userBean); 
									
									$contentTip = "您好，您的密码已经重置:\r\n";
									$contentTip = $contentTip." 用户名:".$userBean ['username'] . " 密码:".$pwd ;
									$weObj->text($contentTip)->reply();
								}else
								{
									$weObj->text('未找到您的相关信息')->reply();
								}
							break;//
							default:
							$wx_weixinmenu_mod = D('weixinmenu');
							$resmenuKeyword = $wx_weixinmenu_mod->where(array('key' => $key))->find();
							if(empty($resmenuKeyword))
							{
								//$weObj->text('其他:'.$key)->reply(); break;
								$weObj->text('请耐心等待菜单生效')->reply(); break;
							}else
							{
								if($resmenuKeyword['keytype']==1)//文字信息
								{
									$contentTextReply = \MyWechatUtil::replaceEmoji(htmlspecialchars_decode($resmenuKeyword['textcontent']));
									$contentTextReply = str_replace("[内部换行]","\r\n",$contentTextReply ) ; 
									$contentTextReply = strip_tags($contentTextReply) ; 
									$weObj->text($contentTextReply)->reply();  break;//文字信息 
								}else if($resmenuKeyword['keytype']==2)
								{
									$weObj->image($resmenuKeyword['media_id'])  ->reply();  break;//图片信息
								}else if($resmenuKeyword['keytype']==3)
								{
									$foverMedia = $weObj->getForeverMedia($resmenuKeyword['media_id']);//图文信息
									$news = array();
									 
									foreach($foverMedia['news_item'] as $foverBean)
									{
										//$foverBean
										$arr  =  array();
										$arr  ['Title'] = $foverBean['title'];
										$arr  ['Description'] = $foverBean['digest'];
										$arr  ['PicUrl'] = $foverBean['thumb_url'];
										$arr   ['Url'] = $foverBean['url'];
										array_push($news,$arr);
									}
									$weObj->news( $news)  ->reply(); 	
								}

								
							}
							
						}
					}else if($eventBean['event'] == \TPWechat::EVENT_SUBSCRIBE)
					{
						//获取场景值
						if($weObj->getRev()->getRevSceneId())
						{
							$parentId = $weObj->getRev()->getRevSceneId();
						}else
						{
							$parentId = 0;
						}
						//提示 
						$contentTip = '';
						//插入用户信息
						$user = M('user');
						$openid = $weObj->getRev()->getRevFrom();
						$whereData ['wxopenid'] = $openid;
						$whereData ['isweixin'] =1 ;
						$lastInsObj =  $user->max('id'); 
						/*if($lastInsObj==null)
						{
							$lastInsId=0;
						}else
						{*/
							$lastInsId=$lastInsObj;
						
						$userBean = $user->where($whereData)->find();
						if(empty($userBean))
						{ 
							$pwd = substr(md5(time()), 0, 6);
							$insertData ['wxopenid'] = $openid;
							$insertData ['username'] = 'itaoke_'.strval($lastInsId+1) ;
							$insertData ['password'] =  md5($pwd);
							$insertData ['reg_time'] = time();
							$insertData ['reg_ip'] = ''; 
							$insertData ['last_time'] = time();
							$insertData ['lastpushtime'] = time();
							$insertData ['isweixin'] = 1;
							$insertData ['parentid'] = $parentId;
							$insertData ['score'] = 0;
							$insertData ['intro'] = '';
							$insertData ['byear'] = 0;
							$insertData ['bmonth'] = 0;
							$insertData ['bday'] = 0;
							$insertData ['province'] = '';
							$insertData ['city'] = '';
							$insertData ['qq'] = '';
							$insertData ['address'] = '';
							$insertData ['realname'] = '';
							
							$insertData ['mobile'] = '';
							$insertData ['sign_time'] = 0; 
							
							$userBaseInfo = $weObj->getUserInfo($openid);
							$insertData ['wxheadpic'] = $userBaseInfo['headimgurl'];
							$insertData ['wxissubscribe'] = $userBaseInfo['subscribe'];
							$insertData ['wxnickname'] = $userBaseInfo['nickname'];
							$insertData ['gender'] = $userBaseInfo['sex'];
							$insertData ['province'] = $userBaseInfo['province'];
							$insertData ['city'] = $userBaseInfo['city'];
							$insertData ['wxsubscribe_time'] = $userBaseInfo['subscribe_time'];
							$insertData ['wxgroupid'] = $userBaseInfo['groupid'];
							$ownId =  $user->add($insertData);	
							
							//是否开启了微信邀请
							if(C('ITK_weixin_is_invite',null,1)==1)
							{
								//那么就开始启动积分机制 
								
								if($parentId==0)
								{ 
									//自己关注 
									$User = M("User")->where('id='.$ownId)->setInc('score',C('itk_wxscore_rule.natural_attention',null,0)); // 用户的积分加
								//	$OtherMSG = '获取关注积分 '.C('itk_wxscore_rule.natural_attention',null,0);
									$OtherMSG = C('itk_wxscore_rule.natural_attention',null,0);
									recordScore($ownId,'wxattention',C('itk_wxscore_rule.natural_attention',null,0)); 
								}else
								{
									//自己 别人推荐关注 
									$User = M("User")->where('id='.$ownId)->setInc('score',C('itk_wxscore_rule.first_attention',null,0)); // 用户的积分加
								//	$OtherMSG = '获取关注积分 '.C('itk_wxscore_rule.first_attention',null,0); 
									$OtherMSG = C('itk_wxscore_rule.first_attention',null,0);
									
									recordScore($ownId,'wxattention',C('itk_wxscore_rule.first_attention',null,0)); 
									//父级 C('itk_wxscore_rule.first_reward',null,0);	  
									$User = M("User")->where('id='.$parentId)->setInc('score',C('itk_wxscore_rule.first_reward',null,0)); // 用户的积分加
									
									recordScore($parentId,'wxinvate',C('itk_wxscore_rule.first_reward',null,0));  
								}
								
							}
							$contentTip=C('itk_wxtips.first');
							$other=array(
								'username'=>$insertData ['username'],
								'pwd'=>$pwd,
								'score'=>$OtherMSG
							);
							$contentTip= wxtips_replace($contentTip,$other);
					//		$contentTip = "Hi，欢迎关注爱淘客系统之前为您自动分配了电脑和手机版通用的帐号:\n".$OtherMSG;
					//		$contentTip = $contentTip." 用户名:".$insertData ['username'] . " 密码：".$pwd;
							
						}else
						{
							//已存在需要提示一下？
							$contentTip=C('itk_wxtips.second');
							$other=array(
								'username'=>$userBean ['username'],
								'pwd'=>'密码无法查看',
							);
							$contentTip= wxtips_replace($contentTip,$other);
			
					//		$contentTip = "Hi，朋友欢迎再次归来，您的电脑和手机版通用的帐号:\r\n";
					//		$contentTip = $contentTip." 用户名:".$userBean ['username'] . " 密码已加密,如果忘记可以重置密码";// ."上级ID:". strval($parentId)
						} 
						$weObj->text($contentTip)->reply();
					}else if($eventBean['event'] == \TPWechat::EVENT_UNSUBSCRIBE)
					{
						 
						$user = M('user');
						$openid = $weObj->getRev()->getRevFrom();
						$whereData ['wxopenid'] = $openid;
 
						$userBean = $user->where($whereData)->find();
						if(!empty($userBean))
						{  
							//是否开启了微信邀请
							if(C('ITK_weixin_is_invite',null,1)==1)
							{
								//那么就开始启动积分机制 
								
								if($userBean['parentid']==0)//bug
								{ 
									//自己关注 
									$User = M("User")->where('id='.$userBean['id'])->setInc('score',C('itk_wxscore_rule.action_cancel_val',null,0));  
									recordScore($userBean['id'],'wxcancel',C('itk_wxscore_rule.action_cancel_val',null,0));
								}else
								{
									//自己 别人推荐关注 
									$User = M("User")->where('id='.$userBean['id'])->setInc('score',C('itk_wxscore_rule.action_cancel_val',null,0));  
									recordScore($userBean['id'],'wxcancel',C('itk_wxscore_rule.action_cancel_val',null,0));
									//父级 
									$User = M("User")->where('id='.$userBean['parentid'])->setInc('score',C('itk_wxscore_rule.cancel_highest_val',null,0)); // 用户的积分加
									
									recordScore($userBean['parentid'],'wxcanhighest',C('itk_wxscore_rule.cancel_highest_val',null,0)); 
									
								}
								
							} 
							
						}
						//$weObj->text("hello, 我是爱淘客小助手 很遗憾你取消关注")->reply();
					} 
					//$weObj->text( '')->reply();  break;//文字信息
					break; 	
			default:
					$weObj->text("hello, 我是爱淘客小助手 输入关键词就可以查询")->reply();
		}
    }
	
	private function _get_top() {
		vendor('Itaoke.TopClient');
		vendor('Itaoke.RequestCheckUtil');
		vendor('Itaoke.Logger');
		$top = new \TopClient;
		$top->appkey = $this->_itkconfig['app_key'];
		$top->secretKey = $this->_itkconfig['app_secret']; 
		return $top;
	}
}